package mainpk;

import java.util.Stack;

/*-------------------------------------------------- 
 * Use a stack to push and pop displayable objects  
 *  
 * public void pushDisplayable(Displayable)  
 * public void popDisplayable()    
 * public void home()  
 *-------------------------------------------------*/
import javax.microedition.lcdui.*;

public class DisplayManager extends Stack {
	private Display display; // Reference to Display object  
	private Displayable mainDisplayable; // Main displayable for MIDlet  
	private Alert alStackError; // Alert for error conditions  

	/*-------------------------------------------------- 
	 * Display manager constructor  
	 *-------------------------------------------------*/
	public DisplayManager(Display display, Displayable mainDisplayable) {
		// Only one display object per midlet, this is it   
		this.display = display;
		this.mainDisplayable = mainDisplayable;

		// Create an alert displayed when an error occurs  
		alStackError = new Alert("Displayable Stack Error");
		alStackError.setTimeout(Alert.FOREVER); // Modal  
	}

	/*-------------------------------------------------- 
	 * Push the current displayable onto stack and set  
	 * the passed in displayable as active  
	 *-------------------------------------------------*/
	public void pushDisplayable(Displayable newDisplayable) {
		push(display.getCurrent());
		display.setCurrent(newDisplayable);
	}

	/*-------------------------------------------------- 
	 * Return to the main displayable object of MIDlet  
	 *-------------------------------------------------*/
	public void home() {
		while (elementCount > 1)
			pop();
		display.setCurrent(mainDisplayable);
	}

	/*-------------------------------------------------- 
	 * Pop displayable from stack and set as active  
	 *-------------------------------------------------*/
	public void popDisplayable() {
		// If the stack is not empty, pop next displayable  
		if (empty() == false)
			display.setCurrent((Displayable) pop());
		else
			// On error show an alert  
			// Once acknowldeged, set 'mainDisplayable' as active  
			display.setCurrent(alStackError, mainDisplayable);
	}

	public Displayable nextDisplayable() {
		return (Displayable) this.lastElement();
	}
}